package org.example.controller;

import org.example.util.jwt.JWTUtil;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Key;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class TokenController {
    public Key key;
    public TokenController(Key key){
        this.key=key;
    }
    @PostMapping("/token")
    public HttpResult<String> login(@RequestParam("username") String username,@RequestParam("password") String password){
        Map<String,Object> claims=new HashMap<>();
        if (username.equals("admin")&&password.equals("admin")){
            claims.put("roles",new String[]{"ADMIN","USER"});
            claims.put("userId",123);
            claims.put("username","admin");
        }else if(username.equals("user")&&password.equals("user")){
            claims.put("roles",new String[]{"USER"});
            claims.put("userId",124);
            claims.put("username","user");
        }else {
            throw new BadCredentialsException("用户名或密码错误");
        }
        Date expDate=Date.from(Instant.now().plusSeconds(1800));
        String token=JWTUtil.generateToken(claims,key,expDate);
        return HttpResult.success(token);
    }
}
